﻿using Avalonia.Styling;
using HslCommunication.Core.Net;
using RoboAssembleX.Application.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Collections.Specialized.BitVector32;

namespace RoboAssembleX.Application.Vision
{
    public class VisionService
    {
        private readonly IEventAggregator eventAggregator;
        CommunicationServer tcpServer;
        List<PipeSession> pipeSessions = new List<PipeSession>();
        public VisionService(IEventAggregator eventAggregator)
        {
            this.eventAggregator = eventAggregator;
        }


        public void InitVisionService()
        {
            tcpServer = new CommunicationServer();
            tcpServer.OnPipeMessageReceived += Server_OnPipeMessageReceived;
            tcpServer.OnClientOnline += Server_OnClientOnline;
            tcpServer.OnClientOffline += Server_OnClientOffline;
            tcpServer.ServerStart(7920);
            eventAggregator.GetEvent<MessageEvent>().Publish(new MessageEventArgs($"Vision服务启动成功", 1));
        }
        public async Task SendVisionCmdAsync(string cmd)
        {
            if (tcpServer!=null && tcpServer.IsStarted && pipeSessions.Count > 0)
            {
                foreach (var item in pipeSessions)
                {
                    byte[] data = Encoding.UTF8.GetBytes(cmd);
                    await item.Communication.SendAsync(data);
                }
            }
        }
        private void Server_OnClientOffline(object server, PipeSession session)
        {
            pipeSessions.Remove(session);
            eventAggregator.GetEvent<MessageEvent>().Publish(new MessageEventArgs($"Vision客户端[{session}]断开连接", 1));
        }

        private void Server_OnClientOnline(object server, PipeSession session)
        {
            pipeSessions.Add(session);
            eventAggregator.GetEvent<MessageEvent>().Publish(new MessageEventArgs($"Vision客户端[{session}]连接成功", 1));
        }

        private void Server_OnPipeMessageReceived(PipeSession session, byte[] buffer)
        {
            eventAggregator.GetEvent<MessageEvent>().Publish(new MessageEventArgs($"收到Vision客户端消息[{session}]：" + Encoding.UTF8.GetString(buffer), 1));
        }
    }
}
